//
//  gTasksAppDelegate.m
//  gTasks
//
//  Created by Verestiuc Vlad Ovidiu on 12/10/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "gTasksAppDelegate.h"

@implementation GTWindow

-(BOOL) canBecomeKeyWindow{
	return YES;
}

@end

@interface GTMenuItem: NSImageView {
@private
	id controller;
}

-(id) initWithController:(id)theController;
@end

@implementation GTMenuItem

-(id) initWithController:(id)theController {
	[[NSStatusBar systemStatusBar] thickness];
	if(self = [super initWithFrame:NSMakeRect(0, 0, [[NSStatusBar systemStatusBar] thickness], 	[[NSStatusBar systemStatusBar] thickness])]){
		controller = theController;
		[self setImage:[NSImage imageNamed:@"gTasksIcon"]];
	}
	return self;
}
- (void)mouseDown:(NSEvent *)event
{
    NSRect frame = [[self window] frame];
    NSPoint pt = NSMakePoint(NSMidX(frame), NSMinY(frame));
    [controller toggleAttachedWindowAtPoint:pt];
    [self setNeedsDisplay:YES];
}
@end


@implementation gTasksAppDelegate

@synthesize window;
@synthesize webView;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	_menuItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
	[_menuItem setView:[[GTMenuItem alloc]initWithController:self]];
	firstTime = YES;
	[window setLevel:NSStatusWindowLevel];
	[window setStyleMask:NSBorderlessWindowMask];


	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(applicationDidLoseFocus) 
												 name:NSApplicationDidResignActiveNotification 
											   object:nil];
}

-(void) applicationDidLoseFocus {
	[window orderOut:nil];
}

- (void) dealloc {
	[_menuItem release];
	[super dealloc];
}

- (void) toggleAttachedWindowAtPoint:(NSPoint) thePoint {
	if( firstTime == YES ) {
		NSRect rect = [window frame];
		rect.origin.x = thePoint.x - rect.size.width/2;
		rect.origin.y = thePoint.y - rect.size.height;	
		[window setFrame:rect display:NO];
		firstTime = NO;
		WebFrame * web = [webView mainFrame];
		[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://mail.google.com/tasks/ig"]]];
		[web reload];		
	}
	
	if( [window isVisible] ){
		[window orderOut:nil];
	}else{
		[window orderFront:self];
		[NSApp activateIgnoringOtherApps:YES];
	}

}
@end




